<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>键盘事件习题</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            width: 100px;
            height: 100px;
            background-color: brown;
            position: absolute;
            text-align: center;
            line-height: 100px;
            top: 0;
        }
    </style>
</head>

<body>
    <script>
        setInterval(function () {
            let divs = document.createElement("div")
            //随机英文字符
            function randomStr() {
                return {
                    // charCodeAt()来获得字符串中某个具体字符的 Unicode 编码
                    // fromCharCode()可接受一个（或多个）指定的 Unicode 值，然后返回对应的字符串
                    divs_text: String.fromCharCode(Math.floor(Math.random() * 26) + 'A'.charCodeAt()) 
                }
            }
            divs.innerHTML = randomStr().divs_text
            //设置div出现的位置
            let lefts = Math.random() * (window.innerWidth - 100)
            // let tops = Math.random() * (window.innerHeight - 100)
            divs.style.left = lefts + "px"
            document.onkeyup = function (ev) {
                // 判断键盘输入是否和div里的值一致
                if (ev.keyCode === divs.innerHTML.charCodeAt()) {
                    divs.remove()
                }
            }
            document.body.appendChild(divs)

            // 控制下降
            let time2 = setInterval(function () {
                // 获取div 初始位置
                let divs_old_top = divs.offsetTop
                // 计算div 新位置
                let divs_new_top = divs_old_top + 2
                // 超出则自动删除
                if (divs_new_top > window.innerHeight - 100) {
                    divs.remove()       
                }
                // 将新值赋值
                divs.style.top = divs_new_top + "px"
            }, 15)
        }, 1500)



    </script>
</body>

</html>